import { createRouter, createWebHistory } from 'vue-router'
import Cookies from 'js-cookie'

// 布局组件
import Layout from '@/layout/index.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '数据统计', requiresAuth: true }
      }
    ]
  },
  {
    path: '/exhibition',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Exhibition',
        component: () => import('@/views/exhibition/index.vue'),
        meta: { title: '展览管理', requiresAuth: true }
      },
      {
        path: 'add',
        name: 'AddExhibition',
        component: () => import('@/views/exhibition/add.vue'),
        meta: { title: '添加展览', requiresAuth: true }
      },
      {
        path: 'edit/:id',
        name: 'EditExhibition',
        component: () => import('@/views/exhibition/edit.vue'),
        meta: { title: '编辑展览', requiresAuth: true }
      }
    ]
  },
  {
    path: '/reservation',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Reservation',
        component: () => import('@/views/reservation/index.vue'),
        meta: { title: '预约管理', requiresAuth: true }
      },
      {
        path: 'detail/:id',
        name: 'ReservationDetail',
        component: () => import('@/views/reservation/detail.vue'),
        meta: { title: '预约详情', requiresAuth: true }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    children: [
      {
        path: '',
        name: 'System',
        component: () => import('@/views/system/index.vue'),
        meta: { title: '系统设置', requiresAuth: true }
      }
    ]
  },
  {
    path: '/review',
    component: Layout,
    redirect: '/review/list',
    name: 'Review',
    meta: { title: '评价管理', icon: 'comment' },
    children: [
      {
        path: 'list',
        name: 'ReviewList',
        component: () => import('@/views/review/index.vue'),
        meta: { title: '评价列表', icon: 'list' }
      }
    ]
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置标题
  document.title = to.meta.title || '博物馆管理系统'
  
  // 判断是否需要登录
  if (to.meta.requiresAuth) {
    const token = Cookies.get('Admin-Token')
    if (token) {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  } else {
    next()
  }
})

export default router
